package co.sanduche.util;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.TextUtils;
import android.util.Log;

public class HttpUtils {
	private static Pattern p = Pattern.compile(":(\\w+)");

	public static String urlInterpolate(String url, Object... objects) {
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < objects.length; i += 2) {
			map.put(objects[i].toString(),
					URLEncoder.encode(objects[i + 1].toString()));
		}
		Matcher m = p.matcher(url);
		StringBuffer sb = new StringBuffer();
		while (m.find()) {
			String key = map.remove(m.group(1));
			if (key != null)
				m.appendReplacement(sb, key);
		}
		m.appendTail(sb);
		List<String> qp = new ArrayList<String>();
		for (Entry<String, String> entry : map.entrySet()) {
			qp.add(entry.getKey() + "=" + entry.getValue());
		}
		String s = TextUtils.join("&", qp);
		if (s.length() > 0)
			sb.append("?").append(TextUtils.join("&", qp));
		Log.e("SanducheUtil.urlInterpolate", sb.toString());
		return sb.toString();
	}
}